import axios, {AxiosResponse} from 'axios'
// @ts-ignore
import qs from 'qs';

// @ts-ignore
import store from '@/conf/store'

import {ElMessage} from "element-plus";

let tipMessage: boolean = true;

const HttpRequest = {
    instance: function (authorization: boolean) {
        //创建axios 实例
        let instance = axios.create({
            baseURL: '/api',
            timeout: 60 * 1000 * 2
        });

        //添加请求拦截器
        instance.interceptors.request.use(
            (config: any) => {
                // 判断一下是否有cookie 如果有的话则把cookie放入请求头中
                if (config.url.indexOf('\'') == -1) {
                    // @ts-ignore
                    console.log(store.getters.token, "axios");
                    if (store.getters.token && authorization) {
                        // @ts-ignore
                        config.headers.authorization = 'bearer ' + store.getters.token;
                    }
                }
                return config;
            },
            (err: any) => {
                console.error(err);
            }
        );

        //添加请求拦截器
        // @ts-ignore
        instance.interceptors.response.use(
            response => {
                return response;
            },
            (error: any) => {
                console.error(error);
                let message = "解析数据异常";
                let response = error.response;
                if (error.response && error.response.status) {
                    const status = error.response.status;
                    switch (status) {
                        case 302:
                            message = '请求重定向';
                        case 400:
                            message = '请求错误';
                            break;
                        case 401:
                            if (response.data.error) {
                                if ("invalid_token" === response.data.error) {
                                    message = "认证已失效"
                                }
                            } else {
                                message = response.data.msg || response.data.body.msg;
                            }
                            // @ts-ignore
                            store.dispatch("logout", true).then(r => {
                                console.log(r)
                            });
                            break;
                        case 403 || 503:
                            if (response.data.error) {
                                message = '服务不可用!';
                            } else {
                                message = response.data.msg || response.data.body.msg;
                            }
                            break;
                        case 404:
                            message = '请求地址出错';
                            break;
                        case 408:
                            message = '请求超时';
                            break;
                        case 500:
                            message = '服务器内部错误!';
                            if (response.data.data) {
                                message = response.data.data
                            }
                            break;
                        case 501:
                            message = '服务未实现!';
                            break;
                        case 502:
                            message = '网关错误!';
                            break;
                        case 504:
                            message = '网关超时!';
                            break;
                        case 505:
                            message = 'HTTP版本不受支持';
                            break;
                        default:
                            message = '请求失败'
                    }
                    if (tipMessage) {
                        tipMessage = false;
                        ElMessage.error(message)
                        setTimeout(function () {
                            tipMessage = true;
                        }, 5000)
                    }
                    return Promise.reject(error);
                }
            }
        );

        return instance;
    },

    /**
     * 发送POST请求
     * @param action 请求地址
     * @param params 参数
     */
    async post(action: string, params: {},): Promise<any> {
        let HttpInstance = this.instance(true);
        return new Promise((resolve, reject) => {
            HttpInstance.post(action, qs.stringify(params, {indices: false}))
                .then((response: any) => {
                    resolve(response.data);
                }, (err: any) => {
                    reject(err);
                });
        })
    },

    tablePost(action: string, params: {},) {
        let HttpInstance = this.instance(true);
        return HttpInstance.post(action, qs.stringify(params, {indices: false}))
    },

    blob(filePath: string) {
        let HttpInstance = this.instance(true);
        return HttpInstance.post("/file/download", qs.stringify({
            filePath: filePath
        }), {responseType: 'blob'})
    },

    /**
     * 下载文件
     * @param action 请求地址
     * @param params {
     *     downloadName:下载后的名称
     *     filePath: 文件所在路径,
     *     data: {} 其他参数 object 类型
     * }
     */
    async download(action: string, params: { downloadName: string; filePath?: string, data?: {} }) {
        let HttpInstance = this.instance(true);

        return new Promise((resolve, reject) => {
            if (!action) {
                action = '/file/download';
            }
            let _params = {
                filePath: params.filePath
            };
            if (params.data) {
                _params = Object.assign(_params, params.data);
            }
            HttpInstance.post(action, qs.stringify(_params), {responseType: 'blob'})
                .then((res: { data: BlobPart; }) => {
                    if (!res) {
                        return;
                    }
                    let url = window.URL.createObjectURL(new Blob([res.data]));
                    let link = document.createElement('a');
                    link.style.display = 'none';
                    link.href = url;
                    link.setAttribute('download', params.downloadName);
                    document.body.appendChild(link);
                    link.click();
                }, (err: any) => {
                    reject(err);
                });
        });
    },

    /**
     * get请求方法
     * @param action 请求地址
     * @param params
     */
    async fetch(action: string, params: any) {
        let HttpInstance = this.instance(true);

        return new Promise((resolve, reject) => {
            HttpInstance.get(action, {
                params: params
            })
                .then((response: { data: AxiosResponse<any> | PromiseLike<AxiosResponse<any>>; }) => {
                    resolve(response.data);
                })
                .catch((err: any) => {
                    reject(err);
                });
        });
    },

    /**
     * 登入请求
     * @param action
     * @param params
     */
    async postNoAuth(action: string, params: any) {
        let HttpInstance = this.instance(false);
        return new Promise((resolve, reject) => {
            HttpInstance.post(action, qs.stringify(params, {indices: false}))
                .then((response: any) => {
                    resolve(response.data);
                }, (err: any) => {
                    reject(err);
                });
        })
    },
    async getNoAuth(action: string) {
        let HttpInstance = this.instance(false);
        return new Promise((resolve, reject) => {
            HttpInstance.post(action).then((response: any) => {
                resolve(response.data);
            }, (err: any) => {
                reject(err);
            });
        })
    },
    async getLocalFile(action: string) {
        let instance = axios.create({
            timeout: 60 * 1000 * 2
        });
        return new Promise((resolve, reject) => {
            instance.post(action).then((response: any) => {
                resolve(response.data);
            }, (err: any) => {
                reject(err);
            });
        })
    },
    /**
     * 发送 jsonBody 请求
     * @param action
     * @param params
     */
    async postJSONBody(action: string, params: any) {
        let HttpInstance = this.instance(true);
        return new Promise((resolve, reject) => {
            HttpInstance.post(action, params, (res: any) => {
                resolve(res)
                // @ts-ignore
            }, () => {
            }, {emulateJSON: false}).catch(e => {
                reject(e)
            })
        })
    },

    /**
     * put请求
     * @param action
     * @param params
     */
    async put(action: string, params: any) {
        let HttpInstance = this.instance(true);
        return new Promise((resolve, reject) => {
            HttpInstance.put(action, params, (res: any) => {
                resolve(res)
                // @ts-ignore
            }, () => {
            }, {emulateJSON: false}).catch(e => {
                reject(e)
            })
        })
    },
    /**
     * delete请求
     * @param action
     * @param params
     */
    async delete(action: string, params: any) {
        let HttpInstance = this.instance(true);
        return new Promise((resolve, reject) => {
            // @ts-ignore
            HttpInstance.delete(action, params).then((response: { data: AxiosResponse<any> | PromiseLike<AxiosResponse<any>>; }) => {
                resolve(response.data);
            }).catch((err: any) => {
                reject(err);
            });
        })
    },
    async logout() {
        let HttpInstance = this.instance(true);
        return new Promise((resolve, reject) => {
            // @ts-ignore
            HttpInstance.post('/cloud/oauth/logout', {}).then((response: { data: AxiosResponse<any> | PromiseLike<AxiosResponse<any>>; }) => {
                localStorage.clear();
                resolve(response.data);
            }).catch((err: any) => {
                reject(err);
            });
        })
    },
    upload(data: FormData) {
        let HttpInstance = this.instance(true);
        return new Promise((resolve, reject) => {
            // @ts-ignore
            HttpInstance.post('/file/uploadFile', data).then((response: any) => {
                resolve(response.data);
            }).catch((err: any) => {
                reject(err);
            });
        })
    },
    getJSON(url: string) {
        let jsonAxios = axios.create({
            timeout: 60000
        });
        jsonAxios.get(url, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'content-type': 'application/json'
            }
        });
        return new Promise((resolve, reject) => {
            jsonAxios.get(url, {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'content-type': 'application/json'
                }
            })
                .then((response: { data: AxiosResponse<any> | PromiseLike<AxiosResponse<any>>; }) => {
                    resolve(response.data);
                })
                .catch((err: any) => {
                    reject(err);
                });
        });
    },
    async imagesSrc(action: string, filePath: any) {
        let HttpInstance = this.instance(true);
        return new Promise((resolve, reject) => {
            if (!action) {
                action = '/file/download';
            }
            HttpInstance.post(action, qs.stringify({filePath: filePath}), {responseType: 'blob'})
                .then((res: { data: BlobPart; }) => {
                    if (!res) {
                        return;
                    }
                    let url = window.URL.createObjectURL(new Blob([res.data]));
                    resolve(url);
                }, (err: any) => {
                    reject(err);
                });
        });
    },

}


export default HttpRequest;
